package email;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailFacade {

    private final Properties mailProperties;

    public EmailFacade(String configFile) {
        mailProperties = new Properties();
        try {
            mailProperties.load(EmailFacade.class.getClassLoader().getResourceAsStream(configFile));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void sendEmail(String address, String subjectKey, String bodyKey, Map<String, String> params) {
        final Session session = Session.getDefaultInstance(mailProperties);
        final MimeMessage message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress("from@no-reply.com"));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(address));
            message.setSubject(parseTemplate(subjectKey, params));
            message.setText(parseTemplate(bodyKey, params));
            Transport.send(message);
            System.out.println(params);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

    private String parseTemplate(String templateKey, Map<String, String> params) {
        String template = mailProperties.getProperty(templateKey);
        for (final Entry<String, String> param : params.entrySet()) {
            template = template.replaceAll("<<" + param.getKey() + ">>", param.getValue());
        }
        return template;
    }
}
